import { useState, useEffect } from 'react';
import { useChatContext } from '../contexts/ChatContext';
import { connectToStream, chatService } from '../services/api';

export function useStreamResponse() {
  const { state, dispatch } = useChatContext();
  const [controller, setController] = useState(null);

  // 发送消息并接收流式响应
  const sendMessageWithStream = async (message) => {
    try {
      // 添加用户消息到聊天
      const userMessage = {
        id: Date.now().toString(),
        role: 'user',
        content: message.text,
        attachments: message.files || [],
        timestamp: new Date(),
      };

      dispatch({ type: 'ADD_MESSAGE', payload: userMessage });
      dispatch({ type: 'SET_LOADING', payload: true });

      // 创建AI回复消息占位
      const aiMessageId = (Date.now() + 1).toString();
      const aiMessage = {
        id: aiMessageId,
        role: 'assistant',
        content: '',
        timestamp: new Date(),
        isStreaming: true,
      };

      dispatch({ type: 'ADD_MESSAGE', payload: aiMessage });

      // 上传文件（如果有）
      let fileUrls = [];
      if (message.files && message.files.length > 0) {
        fileUrls = await Promise.all(
          message.files.map(async file => {
            const url = await chatService.uploadFile(file);
            return url;
          })
        );
      }

      // 准备发送到后端的数据
      const requestData = {
        conversation_id: state.currentConversationId,
        message: message.text,
        model: state.selectedModel,
        attachments: fileUrls.map(url => ({ type: 'image', url })),
      };

      // 连接到流式响应
      let fullContent = '';

      // 调试当前消息状态
      console.log('Current messages before stream:', state.messages);
      console.log('New AI message ID:', aiMessageId);

      const closeStream = connectToStream(
        requestData,
        (data) => {
          if (data.text) {
            fullContent += data.text;
            console.log('Updated content:', fullContent, 'for message ID:', aiMessageId);

            // 使用UPDATE_MESSAGE action更新单个消息
            dispatch({
              type: 'UPDATE_MESSAGE',
              payload: {
                id: aiMessageId,
                updates: {
                  content: fullContent
                }
              }
            });
          } else if (data.content) {
            // 兼容处理，以防有些响应使用content字段
            fullContent += data.content;
            console.log('Updated content (content field):', fullContent, 'for message ID:', aiMessageId);

            // 使用UPDATE_MESSAGE action更新单个消息
            dispatch({
              type: 'UPDATE_MESSAGE',
              payload: {
                id: aiMessageId,
                updates: {
                  content: fullContent
                }
              }
            });
          }
        },
        () => {
          // 流式响应完成
          console.log('Stream completed, setting isStreaming to false for message ID:', aiMessageId);

          dispatch({
            type: 'UPDATE_MESSAGE',
            payload: {
              id: aiMessageId,
              updates: {
                isStreaming: false
              }
            }
          });

          dispatch({ type: 'SET_LOADING', payload: false });
          setController(null);
        },
        (error) => {
          console.error('Stream error:', error);
          dispatch({ type: 'SET_LOADING', payload: false });
          setController(null);
        }
      );

      setController(() => closeStream);

    } catch (error) {
      console.error('发送消息失败', error);
      dispatch({ type: 'SET_LOADING', payload: false });
    }
  };

  // 取消当前流式响应
  const cancelStream = () => {
    if (controller) {
      controller();
      setController(null);
      dispatch({ type: 'SET_LOADING', payload: false });
    }
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (controller) {
        controller();
      }
    };
  }, [controller]);

  return { sendMessageWithStream, cancelStream, isStreaming: !!controller };
}